<template>
  <div class="upload-container">
    <div class="btn-container">
      <!-- <form action="http://10.20.22.50:9099/fileInfo/upload" enctype="multipart/form-data" method="post">
        <input type="text" name="project_id">
        <input id="fileinp" ref="fileUp" class="excel_file" type="file" name="file" :accept="fileType">
        <input type="submit" value="上传">
      </form> -->
      <label id="btn-label" for="fileinp">
        <el-button :size="size" :type="btnType" :icon="icon" :disabled="limit<=fileListLen">
          <template>
            <span>{{ btnTitle }}</span>
          </template>
        </el-button>
        <input
          id="fileinp"
          ref="fileUp"
          class="excel_file"
          :disabled="limit<=fileListLen"
          type="file"
          name="file"
          :accept="fileType"
          multiple
          @change="handleSelect"
        >
      </label>
      <div v-if="tipShow" class="tip"><span>支持上传</span><span
        v-for="(tt, idx) in fileType"
        :key="idx"
      >{{ tt }}{{ fileType.length-1 == idx?'' : '，' }}</span><span>格式的附件</span></div>
    </div>
    <div v-if="showList" class="files-list-container">
      <ul class="files-ul">
        <!-- 已上传至服务器的附件列表 -->
        <li
          v-for="(item, index) in fileList"
          :key="index"
          class="file-item"
          :style="{width: showSize}"
        >
          <div class="pic-container" :style="{width: showSize, height: showSize}">
            <img v-if="item.suffix=='.jpg'||item.suffix=='.jpeg'" :src="jpg" alt="" srcset="">
            <img v-else-if="item.suffix=='.png'" :src="png" alt="" srcset="">
            <img v-else-if="item.suffix=='.doc' || item.suffix=='.docx'" :src="doc" alt="" srcset="">
            <img v-else-if="item.suffix=='.xls'||item.suffix=='.xlsx'" :src="xls" alt="" srcset="">
            <img v-else-if="item.suffix=='.pdf'" :src="pdf" alt="" srcset="">
            <img v-else-if="item.suffix=='.ppt'" :src="ppt" alt="" srcset="">
            <img v-else-if="item.suffix=='.txt'" :src="txt" alt="" srcset="">
            <img v-else-if="item.suffix=='.rar'" :src="rar" alt="" srcset="">
            <img v-else-if="item.suffix=='.zip'" :src="rar" alt="" srcset="">
            <img v-else-if="item.suffix=='.mp4'" :src="rar" alt="" srcset="">
            <div class="file-operation">
              <div class="btn">
                <slot name="btn">
                  <i
                    v-if="fileBtnOption.findIndex((p)=>p==='preview')>-1&&item.suffix!=='.rar'&&item.suffix!=='.zip'"
                    class="icon el-icon-view"
                    @click="handlePreview(item,fileList,index)"
                  />
                  <i
                    v-if="fileBtnOption.findIndex((p)=>p==='edit')>-1&&(item.suffix==='.doc'||item.suffix==='.xls'||item.suffix==='.xlsx'|| item.suffix=='.docx')"
                    class="icon el-icon-edit-outline"
                    @click="handleEdit(item,fileList,index)"
                  />
                  <i
                    v-if="fileBtnOption.findIndex((p)=>p==='delete')>-1"
                    class="icon el-icon-delete"
                    @click="removeItem(item,fileList,index)"
                  />
                </slot>
              </div>
            </div>
          </div>
          <div class="item-name"><span>{{ item.old_name }}{{ item.suffix }}</span></div>
        </li>
        <!-- 新添加的附件，暂未传至服务器 -->
        <li
          v-for="(item, index) in newFileList"
          :key="index+'new'"
          class="file-item"
          :style="{width: showSize}"
        >
          <div class="pic-container" :style="{width: showSize, height: showSize}">
            <img v-if="item.suffix=='.jpg'||item.suffix=='.jpeg'" :src="jpg" alt="" srcset="">
            <img v-else-if="item.suffix=='.png'" :src="png" alt="" srcset="">
            <img v-else-if="item.suffix=='.doc' || item.suffix=='.docx'" :src="doc" alt="" srcset="">
            <img v-else-if="item.suffix=='.xls'||item.suffix=='.xlsx'" :src="xls" alt="" srcset="">
            <img v-else-if="item.suffix=='.pdf'" :src="pdf" alt="" srcset="">
            <img v-else-if="item.suffix=='.ppt'" :src="ppt" alt="" srcset="">
            <img v-else-if="item.suffix=='.txt'" :src="txt" alt="" srcset="">
            <img v-else-if="item.suffix=='.rar'" :src="rar" alt="" srcset="">
            <img v-else-if="item.suffix=='.zip'" :src="rar" alt="" srcset="">
            <img v-else-if="item.suffix=='.mp4'" :src="rar" alt="" srcset="">
            <div class="file-operation">
              <div class="btn">
                <slot name="btn">
                  <i
                    v-if="fileBtnOption.findIndex((p)=>p==='delete')>-1"
                    class="icon el-icon-delete"
                    @click="removeNewItem(item,fileList,index)"
                  />
                </slot>
              </div>
            </div>
          </div>
          <div class="item-name"><span>{{ item.name }}</span></div>
        </li>
      </ul>
    </div>
    <!-- http://vjs.zencdn.net/v/oceans.mp4 -->
    <el-dialog v-if="previewDialog" append-to-body class="preview-dialog" width="1200px" :visible.sync="previewDialog" :close-on-click-modal="false" :title="previewItem.old_name">
      <div class="dialog-main" style="display:flex;justify-content:center;align-items:center;min-height:200px;background: #666;">
        <pdf-preview v-if="previewData.types=='.pdf'&&!isSupportPdf" :urls="previewData.url" />
        <pdf-object v-if="previewData.types=='.pdf'&&isSupportPdf" :urls="previewData.url" />
        <image-preview v-if="previewData.types=='.png'||previewData.types=='.jpg'||previewData.types=='.jpeg'" :currentimg="previewData.url" />
        <audio v-if="previewData.types=='.mp3'||previewData.types=='.wav'" :src="previewData.url" controls :preload="mp4" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fileUpload, fileDelete, dataFlow } from '@/api/upload'
// import { getToken } from '@/utils/auth'
import {
  fileTypeTransform,
  fileListUploadFunc,
  fileListDeleteFunc,
  filePreviewFun,
  fileEditFun,
  blobType
} from '@/utils/file'

import PDFObject from 'pdfobject'

export default {
  components: {
    ImagePreview: () => import('../ImagePreview/index.vue'),
    pdfPreview: () => import('../pdfPreview/index.vue'),
    pdfObject: () => import('../pdfObject/index.vue')
  },
  props: {
    // 可上传附件个数
    limit: {
      type: Number,
      default: 4
    },
    // 按钮名称
    btnTitle: {
      type: String,
      default: '上传附件'
    },
    // 按钮icon
    icon: {
      type: String,
      default: ''
    },
    // 按钮类型--primary，text
    btnType: {
      type: String,
      default: 'primary'
    },
    // 按钮尺寸
    size: {
      type: String,
      default: 'small'
    },
    // 附件预览图标大小
    showSize: {
      type: String,
      default: '120px'
    },
    // 上传附件所需参数
    projectData: {
      type: Object,
      default: () => {
        return {
          project_id: new Date().toLocaleDateString() + ' ' + new Date().getTime(),
          validation: 1
        }
      }
    },
    // 可上传附件的格式
    fileType: {
      type: Array,
      default: () => {
        return ['.jpg', '.jpeg', '.png', '.pdf', '.doc', '.docx', '.xls', '.xlsx']
      }
    },
    // 附件格式提示
    tipShow: {
      type: Boolean,
      default: true
    },
    // 附件预览图列表是否显示
    showList: {
      type: Boolean,
      default: true
    },
    // editList
    editList: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 附件预览、编辑、删除按钮显示控制
    fileBtnOption: {
      type: Array,
      default: () => {
        return ['preview', 'edit', 'delete']
      }
    }
  },
  data() {
    return {
      isSupportPdf: true,
      previewData: {
        url: '',
        name: '',
        types: ''
      },
      userInfo: this.$store.getters.userInfo,
      previewDialog: false,
      previewItem: {},
      fileListLen: 0,
      deleteList: [],
      fileList: [],
      newFileList: [],
      formdata: null,
      jpg: require('@/assets/img/fileTypeIcon/jpg.png'),
      png: require('@/assets/img/fileTypeIcon/png.png'),
      doc: require('@/assets/img/fileTypeIcon/doc.png'),
      xls: require('@/assets/img/fileTypeIcon/xls.png'),
      pdf: require('@/assets/img/fileTypeIcon/pdf.png'),
      ppt: require('@/assets/img/fileTypeIcon/ppt.png'),
      txt: require('@/assets/img/fileTypeIcon/txt.png'),
      zip: require('@/assets/img/fileTypeIcon/zip.png'),
      rar: require('@/assets/img/fileTypeIcon/rar.png'),
      mp4: require('@/assets/img/fileTypeIcon/mp4.png')
    }
  },
  watch: {
    fileList: {
      handler(newVal, oldVal) {
        this.fileListLen = newVal.length
      }
    },
    editList: {
      handler(newval, oldval) {
        if (newval && newval.length) {
          this.fileList = newval
        }
      },
      immediate: true
    }
  },
  created() {
    // console.log(new Date().toLocaleDateString(),new Date().toLocaleTimeString(),new Date().toLocaleString())
  },
  methods: {
    getDataFlow(itemData) {
      const suffix = itemData.suffix.toLowerCase()
      if (suffix === '.jpg' || suffix === '.jpeg' || suffix === '.png' || suffix === '.pdf') {
        const blobtype = blobType(itemData)
        // pdf判断浏览器是否支持
        if (suffix === '.pdf' && PDFObject.supportsPDFs) {
          this.isSupportPdf = true
        } else {
          this.isSupportPdf = false
        }
        dataFlow({ id: itemData.id }).then(res => {
          const src = window.URL.createObjectURL(new Blob([res], {
            type: blobtype
          })) // 这里也是关键,调用window的这个方法URL方法
          this.previewData.url = src
          this.projectData.name = itemData.old_name
          this.previewData.types = itemData.suffix
          this.previewDialog = true
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '您没有访问权限'
          })
        })
      } else {
        this.$message({
          type: 'warning',
          message: '暂不支持在线预览'
        })
      }
    },
    // 返回附件列表数据--已上传成功的
    emitFileList() {
      return this.fileList
    },
    // 返回附件列表数据--已选择未上传的
    emitNewFileList() {
      return this.newFileList
    },
    // 重置附件列表数据
    resetFileList() {
      this.fileList = []
      this.newFileList = []
    },
    handleRemove() {
      return new Promise((resove, reject) => {
        if (!this.deleteList.length) { return }
        fileListDeleteFunc({ ids: this.deleteList })
          .then((res) => {
            if (res.code === 200) {
              this.$emit('deleteSuccess')
              this.$emit('selectSuccess', { fileList: this.fileList, newFileList: this.newFileList })
              resove(this.fileList)
            }
          })
          .catch(() => {
            this.$message({
              type: 'error',
              message: '删除失败'
            })
          })
      })
    },
    removeItem(item, fileList, index) {
      if (this.userInfo && this.userInfo.user && this.userInfo.user.id === item.creator_id) {
        this.fileList.splice(index, 1)
        this.deleteList.push(item.id)
      } else {
        this.$message({
          type: 'error',
          message: '您没有删除操作权限。'
        })
      }
      this.fileListLen = (this.newFileList.length + this.fileList.length)
      this.$emit('selectSuccess', { fileList: this.fileList, newFileList: this.newFileList })
    },
    removeNewItem(item, fileList, index) {
      this.newFileList.splice(index, 1)
      this.fileListLen = (this.newFileList.length + this.fileList.length)
      this.$emit('selectSuccess', { fileList: this.fileList, newFileList: this.newFileList })
    },
    handleSelect(event) {
      const that = this
      console.log(this.$refs.fileUp, event.target.files)
      const list = event.target.files || []
      let counts = 0
      const arr = []
      let errorHint = false
      // 判断有没有上传过
      for (let j = 0; j < list.length; j++) {
        const file_types = fileTypeTransform(list[j])
        const same1 = that.newFileList.findIndex(p => p.type === list[j].type && p.name === list[j].name)
        const same2 = that.fileList.findIndex(p => p.suffix === file_types && (p.old_name + file_types) === list[j].name)
        // console.log('t'+file_types, 's1'+same1, 's2'+same2)
        if (same1 === -1 && same2 === -1) {
          arr.push(list[j])
        } else {
          errorHint = true
        }
      }
      if (errorHint) {
        that.$message({
          type: 'error',
          message: '相同附件不能重复上传!'
        })
      }
      const num = this.limit - (that.newFileList.length + that.fileList.length)
      console.log(that.newFileList)
      for (let i = 0; i < arr.length; i++) {
        // 将附件格式转换为传进来的格式，用于判断
        console.log(arr[i].type)
        const fileType = fileTypeTransform(arr[i])
        that.$set(arr[i], 'suffix', fileType)
        console.log(fileType)
        if (that.fileType.indexOf(fileType) === -1) {
          that.$message({
            type: 'error',
            message: '只能上传特定格式的文件!'
          })
          break
        } else {
          counts++
          if (counts > num) {
            that.$message({
              type: 'error',
              message: `您最多可上传${that.limit}个附件`
            })
            return
          } else {
            that.newFileList.push(arr[i])
          }
        }
      }
      // 解决input type=file 同一个文件二次上传无效的问题
      event.target.value = ''
      console.log(that.newFileList)
      this.fileListLen = (that.newFileList.length + this.fileList.length)
      this.$emit('selectSuccess', { fileList: this.fileList, newFileList: this.newFileList })
    },
    upload() {
      return new Promise((resove, reject) => {
        this.formdata = new FormData()
        let counts = 0
        for (let i = 0; i < this.newFileList.length; i++) {
          counts++
          // 将附件格式转换为传进来的格式，用于判断
          const fileType = fileTypeTransform(this.newFileList[i])
          this.newFileList[i].suffix = fileType
          if (this.fileList.length) {
            const groupId = this.fileList[0].group_id || ''
            this.formdata.append('group_id', groupId)
          }
          if (counts <= this.limit) {
          // 将文件属性放入formdata里面，不能直接使用 this.formdata.append("files",files）
            this.formdata.append('files', this.newFileList[i], this.newFileList[i].name)
            console.log(this.formdata, this.newFileList, this.newFileList[i])
          } else {
            this.$message({
              type: 'error',
              message: `您最多可上传${this.limit}个附件`
            })
          }
        }
        console.log(this.newFileList)
        // // this.formdata.append('files', files)
        // 后台需要的其他参数也一起append进来
        this.formdata.append('project_id', this.projectData.project_id)
        this.formdata.append('validation', this.projectData.validation)
        fileListUploadFunc(this.formdata)
          .then((data) => {
            this.newFileList = []
            this.fileList = this.fileList.concat(data)
            console.log(data, this.fileList)
            this.$emit('uploadSuccess', data)
            resove(this.fileList)
          })
          .catch(() => {
            this.$message({
              type: 'error',
              message: '上传失败，请重新上传。'
            })
          })
      })
    },
    saveFile() {
      return new Promise((resove, reject) => {
        this.saveFile1().then(res => {
          if (res.length > 1) {
            resove([res[0].concat(res[1])])
          } else {
            resove(res)
          }
        })
      })
    },
    // 提交页面数据时---上传附件，如有删除附件（掉删除接口删除）
    saveFile1() {
      if (this.newFileList.length && this.deleteList.length) {
        return Promise.all([this.handleRemove(), this.upload()])
      } else if (this.deleteList.length) {
        return Promise.all([this.handleRemove()])
      } else if (this.newFileList.length) {
        return Promise.all([this.upload()])
      } else {
        return new Promise((resove, reject) => {
          resove([this.fileList])
        })
      }
    },
    handlePreview(item, fileList, index) {
      // this.previewDialog = true
      this.previewItem = item
      if (item.suffix === '.doc' || item.suffix === '.xls' || item.suffix === '.xlsx' || item.suffix == '.docx') {
        filePreviewFun(item)
      } else {
        this.getDataFlow(item)
      }
    },
    handleEdit(item, fileList, index) {
      if (this.userInfo && this.userInfo.user && this.userInfo.user.id === item.creator_id) {
        fileEditFun(item)
      } else {
        this.$message({
          type: 'error',
          message: '您没有编辑操作权限。'
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
@import "@/styles/variables.scss";
.preview-dialog{
  ::v-deep .el-dialog__body{
    padding: 0px 20px 20px;
    max-height: 650px;
    overflow: auto;
    box-sizing: border-box;
  }
  .main-dialog{
    background: #666;
  }
}
.upload-container {
  .btn-container {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    input[type="file"]{
      cursor: pointer;
    }
    input#file-upload-button{
      cursor: pointer;
    }
    #btn-label {
      cursor: pointer;
      position: relative;
      margin-right: 10px;
      #fileinp {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
      }
    }
    .tip {
      font-size: $font-size-main;
      color: $font-color-info;
      margin-left: 10px;
      &:hover {
        cursor: text !important;
      }
    }
  }
  .files-list-container {
    width: 100%;
    .files-ul {
      width: 100%;
      padding: 0px;
      margin: 15px 0px;
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      flex-wrap: wrap;
      .file-item {
        margin-right: 20px;
        overflow: hidden;
        .pic-container {
          min-width: 120px;
          min-height: 120px;
          padding: 5px;
          margin-bottom: 5px;
          border: 1px solid #dcdfe6;
          border-radius: 6px;
          box-sizing: border-box;
          overflow: hidden;
          display: flex;
          justify-content: center;
          align-items: center;
          position: relative;
          img {
            width: 100%;
          }
          &:hover {
            border: 2px solid $main-color;
            .file-operation {
              display: block;
            }
          }
          .file-operation {
            min-width: 120px;
            min-height: 120px;
            border-radius: 6px;
            background: rgba($color: #000000, $alpha: 0.35);
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -60px;
            margin-left: -60px;
            display: none;
            i,
            .icon {
              font-size: 18px;
              color: #fff;
              padding: 5px;
              margin-right: 5px;
              &:last-of-type {
                margin-right: 0px;
              }
              &:hover {
                cursor: pointer;
                color: $main-color;
              }
            }
            .btn {
              min-width: 120px;
              min-height: 120px;
              display: flex;
              justify-content: center;
              align-items: center;
              flex-wrap: wrap;
            }
          }
        }
        .item-name {
          width: 100%;
          font-size: 14px;
          color: #333;
          line-height: 24px;
          overflow: hidden;
          text-overflow: ellipsis;
          word-break: break-word;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          display: -webkit-box;
        }
      }
    }
  }
}
</style>
